package com.huabo.contract.service.impl;

import java.math.BigDecimal;
import java.util.*;

import javax.annotation.Resource;

import com.huabo.contract.config.DateBaseConfig;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSONObject;
import com.hbfk.entity.DealUserToken;
import com.hbfk.entity.TblStaffUtil;
import com.hbfk.util.JedisUtil;
import com.hbfk.util.JwtUtils;
import com.hbfk.util.Md5util;
import com.hbfk.util.PageInfo;
import com.huabo.contract.oracle.entity.TblFormElements;
import com.huabo.contract.oracle.entity.TblLoginType;
import com.huabo.contract.oracle.entity.TblOrganization;
import com.huabo.contract.oracle.entity.TblStaff;
import com.huabo.contract.oracle.mapper.TblLogintypeMapper;
import com.huabo.contract.oracle.mapper.TblOrganizationMapper;
import com.huabo.contract.oracle.mapper.TblStaffMapper;
import com.huabo.contract.service.TblStaffService;
import com.huabo.contract.util.HttpClient;

import lombok.extern.slf4j.Slf4j;
import net.sf.json.JSONArray;
import redis.clients.jedis.Jedis;


@Service("tblStaffServiceImpl")
@Slf4j
public class TblStaffServiceImpl implements TblStaffService {

	private static final String formurl= ResourceBundle.getBundle("setting/process").getString("formurl").toString();

	@Resource
	public TblStaffMapper tblStaffMapper;

	@Resource
	public TblOrganizationMapper tblOrganizationMapper;

	@Resource
	public TblLogintypeMapper tblLogintypeMapper;

	public Map<String,Object> dealLoginSystem(String userName, String password, String loginType, String verifyCode, String verid)
			throws Exception {
		if(DateBaseConfig.DATABASETYPE.equals("Oracle")) {
			Jedis jedis = null;
			Map<String, Object> resultMap = new HashMap<String, Object>(0);
			Map<String, Object> dataMap = new HashMap<String, Object>(0);
			try {
				jedis = JedisUtil.getJedis();

				log.info("根据用户名密码 获取用户" + userName + "信息");
				TblStaff staff = this.tblStaffMapper.selectUniqueStaffInfo(userName, Md5util.encrypByMd5(password));
				if (staff == null) {
					resultMap.put("code", "0");
					resultMap.put("msg", "用户名或密码错误！");
					log.info(userName + "用户名或密码错误！");
					return resultMap;
				}

				TblOrganization linkOrg = this.tblOrganizationMapper.selectCompanyInfoByDeptId(staff.getLinkDetp().getOrgid());
				staff.setLinkOrg(linkOrg);
				staff.setCurrentOrg(linkOrg);

				TblLoginType logintype = this.tblLogintypeMapper.selectLoginTypeInfo("/" + loginType);
				log.info("查询用户登录页面信息，返回结果");
				staff.setLoginType(logintype);

				Map<String, Object> tokenMap = new HashMap<String, Object>(0);
				tokenMap.put("staffInfo", staff);
				String token = JwtUtils.createJwt(staff.getStaffid().toString(), staff.getRealname(), tokenMap);

				jedis.set(staff.getStaffid().toString(), token);

				resultMap.put("code", "1");
				dataMap.put("staffInfo", staff);
				dataMap.put("token", token);
				resultMap.put("msg", "用户登录成功");
				resultMap.put("data", dataMap);
				log.info("用户登录成功，返回用户信息、token");
			} catch (Exception e) {
				e.printStackTrace();
			} finally {
				if (jedis != null) {
					jedis.close();
				}
			}

			return resultMap;
		} else {
			Jedis jedis = null;
			Map<String, Object> resultMap = new HashMap<String, Object>(0);
			Map<String, Object> dataMap = new HashMap<String, Object>(0);
			try {
				jedis = JedisUtil.getJedis();

				log.info("根据用户名密码 获取用户" + userName + "信息");
				TblStaff staff = this.tblStaffMapper.selectUniqueStaffInfo(userName, Md5util.encrypByMd5(password));
				if (staff == null) {
					resultMap.put("code", "0");
					resultMap.put("msg", "用户名或密码错误！");
					log.info(userName + "用户名或密码错误！");
					return resultMap;
				}

				TblOrganization linkOrg = this.tblOrganizationMapper.selectCompanyInfoByDeptId(staff.getLinkDetp().getOrgid());
				staff.setLinkOrg(linkOrg);
				staff.setCurrentOrg(linkOrg);

				TblLoginType logintype = this.tblLogintypeMapper.selectLoginTypeInfo("/" + loginType);
				log.info("查询用户登录页面信息，返回结果");
				staff.setLoginType(logintype);

				Map<String, Object> tokenMap = new HashMap<String, Object>(0);
				tokenMap.put("staffInfo", staff);
				String token = JwtUtils.createJwt(staff.getStaffid().toString(), staff.getRealname(), tokenMap);

				jedis.set(staff.getStaffid().toString(), token);

				resultMap.put("code", "1");
				dataMap.put("staffInfo", staff);
				dataMap.put("token", token);
				resultMap.put("msg", "用户登录成功");
				resultMap.put("data", dataMap);
				log.info("用户登录成功，返回用户信息、token");
			} catch (Exception e) {
				e.printStackTrace();
			} finally {
				if (jedis != null) {
					jedis.close();
				}
			}

			return resultMap;
		}
	}


    @Override
    public Map<String, Object> findAllPageBeanPid(Integer pageNumber, Integer pageSize, BigDecimal orgid,TblOrganization organization) {
		if(DateBaseConfig.DATABASETYPE.equals("Oracle")) {
			Map<String, Object> resultMap = new HashMap<String, Object>(0);

			PageInfo<TblStaff> pageInfo = new PageInfo<TblStaff>();
			pageInfo.setCurrentPage(pageNumber);
			pageInfo.setPageSize(pageSize);
			pageInfo.setTlist(tblStaffMapper.selectListByPageInfo(pageInfo, orgid, organization));
			pageInfo.setTotalRecord(tblStaffMapper.selectListByPageInfoCount(orgid, organization));

//		PageInfo findByPageBeanObj = this.tblStaffMapper.selectListByPage(pageInfo,orgid,organization);
//		if (findByPageBeanObj.getTlist() != null && findByPageBeanObj.getTlist().size() > 0) {
//			List<Object[]> recordList = findByPageBeanObj.getTlist();
//			List<TblStaff> users = new ArrayList();
//			Iterator var9 = recordList.iterator();
//
//			while(var9.hasNext()) {
//				Object[] objects = (Object[])var9.next();
//				TblStaff user = new TblStaff();
//				TblOrganization org = new TblOrganization();
//				user.setStaffid(new BigDecimal(objects[0].toString()));
//				user.setRealname(objects[1].toString());
//				user.setAddress(objects[4] != null ? objects[4].toString() : "");
//				user.setEmail(objects[5] != null ? objects[5].toString() : "");
//				org.setOrgid(new BigDecimal(objects[2].toString()));
//				org.setOrgname(objects[3].toString());
//				user.setLinkOrg(org);
//				user.setUsername(objects[6].toString());
//				users.add(user);
//			}
//
//			findByPageBeanObj.setTlist(users);
//		}

			resultMap.put("code", "1");
			resultMap.put("msg", "访问接口成功");
			resultMap.put("pageInfo", pageInfo);
			return resultMap;
		} else {
			Map<String, Object> resultMap = new HashMap<String, Object>(0);

			PageInfo<TblStaff> pageInfo = new PageInfo<TblStaff>();
			pageInfo.setCurrentPage(pageNumber);
			pageInfo.setPageSize(pageSize);
			pageInfo.setTlist(tblStaffMapper.selectListByPageInfo(pageInfo, orgid, organization));
			pageInfo.setTotalRecord(tblStaffMapper.selectListByPageInfoCount(orgid, organization));

//		PageInfo findByPageBeanObj = this.tblStaffMapper.selectListByPage(pageInfo,orgid,organization);
//		if (findByPageBeanObj.getTlist() != null && findByPageBeanObj.getTlist().size() > 0) {
//			List<Object[]> recordList = findByPageBeanObj.getTlist();
//			List<TblStaff> users = new ArrayList();
//			Iterator var9 = recordList.iterator();
//
//			while(var9.hasNext()) {
//				Object[] objects = (Object[])var9.next();
//				TblStaff user = new TblStaff();
//				TblOrganization org = new TblOrganization();
//				user.setStaffid(new BigDecimal(objects[0].toString()));
//				user.setRealname(objects[1].toString());
//				user.setAddress(objects[4] != null ? objects[4].toString() : "");
//				user.setEmail(objects[5] != null ? objects[5].toString() : "");
//				org.setOrgid(new BigDecimal(objects[2].toString()));
//				org.setOrgname(objects[3].toString());
//				user.setLinkOrg(org);
//				user.setUsername(objects[6].toString());
//				users.add(user);
//			}
//
//			findByPageBeanObj.setTlist(users);
//		}

			resultMap.put("code", "1");
			resultMap.put("msg", "访问接口成功");
			resultMap.put("pageInfo", pageInfo);
			return resultMap;
		}
    }

    @Override
    public Map<String, Object> findAllPageBeanPid(String pid, Integer pageNumber, Integer pageSize, String token, String staffId) {
		if(DateBaseConfig.DATABASETYPE.equals("Oracle")) {
			Map<String, Object> resultMap = new HashMap<String, Object>(0);
			try {
				Map<String, Object> dataMap = new HashMap<String, Object>(0);
				TblStaffUtil user = DealUserToken.parseUserToken(token);
				if (user == null) {
					resultMap.put("code", "0");
					resultMap.put("msg", "用户已失效！");
					return resultMap;
				}
				TblOrganization attribute = new TblOrganization();
				if (pid != null && !pid.equals("")) {
					attribute = tblOrganizationMapper.findById(new BigDecimal(pid));
				} else {
					attribute.setOrgid(user.getCurrentOrg().getOrgid());
					attribute.setOrgtype(user.getCurrentOrg().getOrgtype());
				}
				PageInfo<TblStaff> pageInfo = new PageInfo<TblStaff>();
				pageInfo.setCurrentPage(pageNumber);
				pageInfo.setPageSize(pageSize);
				pageInfo.setTlist(tblStaffMapper.findAllPageBeanPid(pageInfo, attribute));
				pageInfo.setTotalRecord(tblStaffMapper.findAllCountPageBeanPid(pageInfo, attribute));
				dataMap.put("pageInfo", pageInfo);
				dataMap.put("attribute", attribute);
				resultMap.put("code", "1");
				resultMap.put("msg", "访问接口成功");
				resultMap.put("pageInfo", dataMap);
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			return resultMap;
		} else {
			Map<String, Object> resultMap = new HashMap<String, Object>(0);
			try {
				Map<String, Object> dataMap = new HashMap<String, Object>(0);
				TblStaffUtil user = DealUserToken.parseUserToken(token);
				if (user == null) {
					resultMap.put("code", "0");
					resultMap.put("msg", "用户已失效！");
					return resultMap;
				}
				TblOrganization attribute = new TblOrganization();
				if (pid != null && !pid.equals("")) {
					attribute = tblOrganizationMapper.findById(new BigDecimal(pid));
				} else {
					attribute.setOrgid(user.getCurrentOrg().getOrgid());
					attribute.setOrgtype(user.getCurrentOrg().getOrgtype());
				}
				PageInfo<TblStaff> pageInfo = new PageInfo<TblStaff>();
				pageInfo.setCurrentPage(pageNumber);
				pageInfo.setPageSize(pageSize);
				pageInfo.setTlist(tblStaffMapper.findAllPageBeanPid(pageInfo, attribute));
				pageInfo.setTotalRecord(tblStaffMapper.findAllCountPageBeanPid(pageInfo, attribute));
				dataMap.put("pageInfo", pageInfo);
				dataMap.put("attribute", attribute);
				resultMap.put("code", "1");
				resultMap.put("msg", "访问接口成功");
				resultMap.put("pageInfo", dataMap);
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			return resultMap;
		}
    }

    @Override
    public Map<String, Object> findHttpClient(Integer formId, String jsonArry, String paramArry, String eleName, String valueId, Integer pageNumber, Integer pageSize, Integer queryType, Integer oldFormId, String textname) {
		if(DateBaseConfig.DATABASETYPE.equals("Oracle")) {
			Map<String, Object> resultMap = new HashMap<String, Object>(0);
			Map<String, Object> dataMap = new HashMap<String, Object>(0);
			try {
				HashMap<String, Object> fields = new HashMap<String, Object>(0);
				fields.put("formId", formId);
				fields.put("pageNumber", pageNumber);
				fields.put("pageSize", pageSize);
				fields.put("queryType", queryType);
				fields.put("oldFormId", oldFormId);
				fields.put("eleName", textname);
				if (jsonArry != null && !"".equals(jsonArry) && jsonArry.length() > 2) {
					jsonArry = jsonArry.substring(0, jsonArry.length() - 1) + ",[\"VALUESTATUS\",\"等于\",\"6\"]]";
				} else {
					jsonArry = "[[\"VALUESTATUS\",\"等于\",\"6\"]]";
				}
				fields.put("jsonArry", jsonArry);
				String result = HttpClient.request(formurl + "/formReport/findFormReportList", fields, null);
				JSONObject resultjs = JSONObject.parseObject(result);

				PageInfo<TblFormElements> pageInfo = new PageInfo<TblFormElements>();
				if ("true".equals(resultjs.get("result").toString())) {
					pageInfo.setTotalRecord(Integer.parseInt(resultjs.get("count").toString()));
					com.alibaba.fastjson.JSONArray array = resultjs.getJSONArray("mapList");
					dataMap.put("array", array);
					String eleListstr = resultjs.get("eleList").toString();
					List<TblFormElements> eleList = JSONObject.parseArray(eleListstr, TblFormElements.class);
					dataMap.put("eleList", eleListstr);
					dataMap.put("eleLists", eleList);
					dataMap.put("formName", resultjs.get("formName").toString());
				} else {
					pageInfo.setTotalRecord(0);
				}
				pageInfo.setCurrentPage(pageNumber);
				dataMap.put("formId", formId);
				dataMap.put("pageInfo", pageInfo);
			} catch (Exception e) {
				e.printStackTrace();
			}
			dataMap.put("eleName", eleName);
			dataMap.put("valueId", valueId);
			dataMap.put("arrayMap", printJsonArray(jsonArry, paramArry));
			resultMap.put("code", "1");
			resultMap.put("msg", "访问接口成功");
			resultMap.put("data", dataMap);
			return resultMap;
		} else {
			Map<String, Object> resultMap = new HashMap<String, Object>(0);
			Map<String, Object> dataMap = new HashMap<String, Object>(0);
			try {
				HashMap<String, Object> fields = new HashMap<String, Object>(0);
				fields.put("formId", formId);
				fields.put("pageNumber", pageNumber);
				fields.put("pageSize", pageSize);
				fields.put("queryType", queryType);
				fields.put("oldFormId", oldFormId);
				fields.put("eleName", textname);
				if (jsonArry != null && !"".equals(jsonArry) && jsonArry.length() > 2) {
					jsonArry = jsonArry.substring(0, jsonArry.length() - 1) + ",[\"VALUESTATUS\",\"等于\",\"6\"]]";
				} else {
					jsonArry = "[[\"VALUESTATUS\",\"等于\",\"6\"]]";
				}
				fields.put("jsonArry", jsonArry);
				String result = HttpClient.request(formurl + "/formReport/findFormReportList", fields, null);
				JSONObject resultjs = JSONObject.parseObject(result);

				PageInfo<TblFormElements> pageInfo = new PageInfo<TblFormElements>();
				if ("true".equals(resultjs.get("result").toString())) {
					pageInfo.setTotalRecord(Integer.parseInt(resultjs.get("count").toString()));
					com.alibaba.fastjson.JSONArray array = resultjs.getJSONArray("mapList");
					dataMap.put("array", array);
					String eleListstr = resultjs.get("eleList").toString();
					List<TblFormElements> eleList = JSONObject.parseArray(eleListstr, TblFormElements.class);
					dataMap.put("eleList", eleListstr);
					dataMap.put("eleLists", eleList);
					dataMap.put("formName", resultjs.get("formName").toString());
				} else {
					pageInfo.setTotalRecord(0);
				}
				pageInfo.setCurrentPage(pageNumber);
				dataMap.put("formId", formId);
				dataMap.put("pageInfo", pageInfo);
			} catch (Exception e) {
				e.printStackTrace();
			}
			dataMap.put("eleName", eleName);
			dataMap.put("valueId", valueId);
			dataMap.put("arrayMap", printJsonArray(jsonArry, paramArry));
			resultMap.put("code", "1");
			resultMap.put("msg", "访问接口成功");
			resultMap.put("data", dataMap);
			return resultMap;
		}
    }

	public JSONObject printJsonArray(String jsonArry,String paramArry){
		if(DateBaseConfig.DATABASETYPE.equals("Oracle")) {
			JSONObject object = new JSONObject();
			if (jsonArry != null) {
				JSONArray jsonArray = JSONArray.fromObject(jsonArry);
				Object[] objs = null;
				for (int i = 0; i < jsonArray.size(); i++) {
					objs = jsonArray.getJSONArray(i).toArray();
					object.put(objs[0].toString(), objs[2].toString());
				}
			}
			if (paramArry != null) {
				JSONArray paramArray = JSONArray.fromObject(paramArry);
				Object[] objs = null;
				for (int i = 0; i < paramArray.size(); i++) {
					objs = paramArray.getJSONArray(i).toArray();
					object.put(objs[0].toString(), objs[2].toString());
				}
			}
			return object;
		} else {
			JSONObject object = new JSONObject();
			if (jsonArry != null) {
				JSONArray jsonArray = JSONArray.fromObject(jsonArry);
				Object[] objs = null;
				for (int i = 0; i < jsonArray.size(); i++) {
					objs = jsonArray.getJSONArray(i).toArray();
					object.put(objs[0].toString(), objs[2].toString());
				}
			}
			if (paramArry != null) {
				JSONArray paramArray = JSONArray.fromObject(paramArry);
				Object[] objs = null;
				for (int i = 0; i < paramArray.size(); i++) {
					objs = paramArray.getJSONArray(i).toArray();
					object.put(objs[0].toString(), objs[2].toString());
				}
			}
			return object;
		}
	}

    @Override
    public TblStaff findById(String staffid) {
		if(DateBaseConfig.DATABASETYPE.equals("Oracle")) {
			return tblStaffMapper.findByStaffid(staffid);
		} else {
			return tblStaffMapper.findByStaffid(staffid);
		}
    }

    @Override
    public void updateTs(TblStaff ts) {
		if(DateBaseConfig.DATABASETYPE.equals("Oracle")) {
			tblStaffMapper.updateTs(ts);
		} else {
			tblStaffMapper.updateTs(ts);
		}
    }

    @Override
    public void saveTs(TblStaff ts) {
		if(DateBaseConfig.DATABASETYPE.equals("Oracle")) {
			this.tblStaffMapper.saveTs(ts);
		} else {
			this.tblStaffMapper.saveTs(ts);
		}
    }

	@Override
	public TblStaff findByRolename(String rolename, String orgid) {
		if(DateBaseConfig.DATABASETYPE.equals("Oracle")) {
			return tblStaffMapper.findByRolename(rolename, orgid);
		} else {
			return tblStaffMapper.findByRolename(rolename, orgid);
		}
	}
	public TblStaff findByJobName(String jobname, String orgid){
		if(DateBaseConfig.DATABASETYPE.equals("Oracle")) {
			return tblStaffMapper.findByJobName(jobname, orgid);
		} else {
			return tblStaffMapper.findByJobName(jobname, orgid);
		}
	}
	public TblStaff findByStaffManOrgs(String orgid){
        TblStaff bmfzr = tblStaffMapper.findByStaffManOrgs(orgid);
			return bmfzr;
	}
    public TblStaff getHistorycode(String historycode) {
		if(DateBaseConfig.DATABASETYPE.equals("Oracle")) {
			TblStaff tblStaff = tblStaffMapper.getHistorycode(historycode);
			return tblStaff;
		} else {
			TblStaff tblStaff = tblStaffMapper.getHistorycode(historycode);
			return tblStaff;
		}
    }
    
}
